package com.baofu.paycore.manager.storage.impl;

import com.baofu.paycore.common.enums.OperatorEnum;
import com.baofu.paycore.common.exception.ManagerErrorCode;
import com.baofu.paycore.common.exception.PayCoreManagerException;
import com.baofu.paycore.manager.model.SubPayBO;
import com.baofu.paycore.dal.mapper.SubPayMapper;
import com.baofu.paycore.dal.model.SubPayDO;
import com.baofu.paycore.manager.storage.Storage;
import com.baofu.paycore.service.facade.enums.PayCoreErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 支付子单存储
 *
 * <p/>
 *      1、新增订单
 *      2、更新订单
 *      3、废弃订单
 * </p>
 * User: LZQ Date: 2016/04/21  Version: 1.0
 */
@Slf4j
@Repository
public class SubPayManager implements Storage<SubPayDO> {

    /**
     * 支付资金单Mapper
     */
    @Autowired
    private SubPayMapper subPayMapper;

    /**
     * 新增订单
     *
     * @param subPayDO 订单信息
     */
    @Override
    public int addOrder(SubPayDO subPayDO) {

       return subPayMapper.insert(subPayDO);
    }

    /**
     * 更新订单
     *
     * @param subPayDO 订单信息
     */
    @Override
    public int modifyOrder(SubPayDO subPayDO) {
        if (StringUtils.isNotBlank(subPayDO.getErrorReason()) && subPayDO.getErrorReason().length() > 125) {
            subPayDO.setErrorReason(subPayDO.getErrorReason().substring(0, 125));
        }
        return subPayMapper.updateSubPay(subPayDO);
    }

    /**
     * 废弃订单
     *
     * @param subPayDO 订单信息
     */
    @Override
    public int deleteOrder(SubPayDO subPayDO) {
        return 0;
    }

    /**
     * 更新订单
     *
     * @param subPayBO 订单信息
     */
    public void modifyRefundAmt(SubPayBO subPayBO) {

        log.debug("更新支付资金明细单退款金额, parameter:{}",subPayBO);
        int updateRows = subPayMapper.updateRefundAmt(subPayBO.getFundDetailNo(), subPayBO.getRefundAmount(),
                OperatorEnum.UPDATED_BY.getCode());
        if(updateRows > 1){
            log.error("支付资金明细单退款金额更新失败, error:{}", PayCoreErrorCode.UPDATE_DATA_NOT_ONE);
            throw new PayCoreManagerException(PayCoreErrorCode.UPDATE_DATA_NOT_ONE);
        }
    }

    /**
     * 依支付单号查询支付子单信息
     *
     * @param payNo         支付单号
     * @return              支付子单信息
     */
    public List<SubPayDO> selectSubPay(String payNo){

        log.info("查询支付子单信息 payNo:{}", payNo);
        return subPayMapper.selectByPayNo(payNo);
    }
}
